package com.zhentao.service.Impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.mapper.WmUserMapper;
import com.zhentao.model.dtos.ResponseResult;
import com.zhentao.model.enums.AppHttpCodeEnum;
import com.zhentao.model.wemedia.dto.WmLogindto;
import com.zhentao.model.wemedia.pojo.WmUser;
import com.zhentao.service.WmUserService;
import com.zhentao.utils.common.AppJwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {


    @Autowired
    private WmUserMapper userMapper;

    @Override
    public ResponseResult login(WmLogindto wmLogindto) {
        if (StringUtils.isBlank(wmLogindto.getName()) || StringUtils.isBlank(wmLogindto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "账号和密码不存在");
        }


        WmUser wmUser = userMapper.selectOne(new LambdaQueryWrapper<WmUser>()
                .eq(WmUser::getName, wmLogindto.getName()));
        if (wmUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "账号不存在");
        }

        String pwd = DigestUtils.md5DigestAsHex((wmLogindto.getPassword() + wmUser.getSalt()).getBytes(StandardCharsets.UTF_8));
        if (pwd.equals(wmUser.getPassword())) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("token", AppJwtUtil.getToken(wmUser.getId().longValue()));
            wmUser.setPassword(null);
            wmUser.setSalt(null);
            map.put("user", wmUser);
            return ResponseResult.okResult(map);
        } else {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "密码错误");
        }

    }
}
